import java.util.Stack;

//栈_字符串解码
//https://leetcode.cn/problems/decode-string/description/
public class Test {
    public static void main(String[] args) {
        //
    }
}


//自己写：还没有写出来
class Solution1 {
    public String decodeString(String s) {
        //两个栈，看似复杂，其实简单省事
        Stack<String> stackS = new Stack<>();
        Stack<Integer> stackN = new Stack<>();
        stackS.push("");//一种处理，方便后续的操作
        int n = s.length();
        char[] chars = s.toCharArray();
        for(int i = 0; i < n; ){
            //分情况讨论
            char c = s.charAt(i);//c与i相结合的判断、更新策略
            if(c == '['){
                i++;
                //stackS.push("[");
                //提取字符串
                StringBuffer sb = new StringBuffer();
                while(chars[i] != ']'){
                    sb.append(chars[i]);
                    i++;
                }
                //将提取出来的字符串加到栈顶元素的后边
                stackS.push(stackN.pop()+sb.toString());
            }else if(c == ']'){
                //字符串解码
                //字符串放回
            }else if(c >= '0' && c <= '9'){
                stackN.push(c - '0');
            }else{//遇到单独的字符串
                //提取字符串
                //放到栈顶元素后边

            }
        }
    }
}



//课件上的代码：
class Solution
{
    public String decodeString(String _s)
    {
        Stack<StringBuffer> st = new Stack<>();
        st.push(new StringBuffer()); // 先放⼀个空串进去
        Stack<Integer> nums = new Stack<>();
        int i = 0, n = _s.length();
        char[] s = _s.toCharArray();
        while(i < n)
        {
            if(s[i] >= '0' && s[i] <= '9')
            {
                int tmp = 0;
                while(i < n && s[i] >= '0' && s[i] <= '9')
                {
                    tmp = tmp * 10 + (s[i] - '0');
                    i++;
                }
                nums.push(tmp);
            }
            else if(s[i] == '[')
            {
                i++; // 把后⾯的字符串提取出来
                StringBuffer tmp = new StringBuffer();
                while(i < n && s[i] >= 'a' && s[i] <= 'z')
                {
                    tmp.append(s[i]);
                    i++;
                }
                st.push(tmp);
            }
            else if(s[i] == ']')
            {
                // 解析

                StringBuffer tmp = st.pop();
                int k = nums.pop();
                while(k-- != 0)
                {
                    st.peek().append(tmp);
                }
                i++;
            }
            else
            {
                StringBuffer tmp = new StringBuffer();
                while(i < n && s[i] >= 'a' && s[i] <= 'z')
                {
                    tmp.append(s[i]);
                    i++;
                }
                st.peek().append(tmp);
            }
        }
        return st.peek().toString();
    }
}
